package org.lynn.db.service;

import org.lynn.db.dao.CustomerRepository;
import org.lynn.db.domain.Customer;
import org.lynn.db.domain.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author gy
 * @date 2019/1/6 14:16
 */
@Service
public class CustomerService {

    @Autowired
    private CustomerRepository customerRepository;

//    @Autowired
//    @Qualifier("userJdbcTemplate")
//    private JdbcTemplate userJdbcTemplate;

    @Autowired
    @Qualifier("orderJdbcTemplate")
    private JdbcTemplate orderJdbcTemplate;

    private static final String SQL_UPDATE_DEPOSIT = "UPDATE customer SET deposit = deposit - ? where id = ?";
    private static final String SQL_CREATE_ORDER = "INSERT INTO customer_order (customer_id,title,amount) VALUES (?,?,?)";

    @Transactional(rollbackFor = Exception.class)
    public void createOrder(Order order) {

        Customer customer = customerRepository.findOne(order.getCustomerId());
        customer.setDeposit(customer.getDeposit() - order.getAmount());
        customerRepository.save(customer);

//        userJdbcTemplate.update(SQL_UPDATE_DEPOSIT, order.getAmount(), order.getCustomerId());
        if (order.getTitle().contains("error1")) {
            throw new RuntimeException("error1");
        }
        orderJdbcTemplate.update(SQL_CREATE_ORDER, order.getCustomerId(), order.getTitle(), order.getAmount());
        if (order.getTitle().contains("error2")) {
            throw new RuntimeException("error2");
        }
    }

    public Map userInfo(Long customerId) {

        Customer customer = customerRepository.findOne(customerId);

//        Map customer = userJdbcTemplate.queryForMap("SELECT * FROM customer WHERE id = " + customerId);
        List orders = orderJdbcTemplate.queryForList("SELECT * FROM customer_order WHERE customer_id = " + customerId);

        Map result = new HashMap();

        result.put("customer", customer);
        result.put("orders", orders);

        return result;

    }


}
